package com.lechi.web.server.connect;

import com.lechi.iot.netty.channel.ITcpChannel;
import com.lechi.iot.netty.device.TcpDeviceChannel;
import com.lechi.iot.netty.utils.NettyCacheUtils;
import com.lechi.web.constants.AppCmdConstants;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.service.impl.IotDeviceCommond;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 服务端链接管理器,处理接受数据
 */
@Slf4j
@Sharable
public class TcpServerConnect extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //成功后，重连失败次数清零
        Channel channel = ctx.channel();
        ctx.fireChannelActive();
        if (Objects.nonNull(channel.remoteAddress())) {
            String hostName = channel.remoteAddress().toString();
            log.error("MODBUS-TCP服务和传感器设备地址：{} 建立链接", hostName);
            ITcpChannel tcpChannel = new TcpDeviceChannel(channel);
            NettyCacheUtils.put(hostName, tcpChannel);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ctx.fireChannelInactive();
        Channel channel = ctx.channel();
        if (Objects.nonNull(channel) && Objects.nonNull(channel.remoteAddress())) {
            String hostName = channel.remoteAddress().toString();
            log.error("MODBUS-TCP服务和传感器设备地址：{} 断开链接！", hostName);
            ITcpChannel tcpChannel = NettyCacheUtils.get(hostName, ITcpChannel.class);
            if (Objects.nonNull(tcpChannel) && Objects.nonNull(tcpChannel.getDeviceSn())) {
                CompletableFuture.runAsync(IotDeviceCommond.commond(tcpChannel.getDeviceSn(), AppCmdConstants.STOPED));
                GuavaCacheUtil.getBiDeviceSnAndIPMap().remove(tcpChannel.getDeviceSn());
            }
            NettyCacheUtils.remove(hostName);
            //连接断开后的最后处理
            ctx.pipeline().remove(ctx.handler());
            ctx.deregister();
            ctx.close();
        }
    }
}
